from jili.tool.convert import str2datetime
import datetime
import pandas as pd
# 假设我们有一个日期
date = pd.to_datetime('2023-01-15')

# 加上2个月
new_date_plus = date + pd.DateOffset(months=2)
def iter_start_end(start,end,by="year",n=1):#按月  #按年
    if by=="year":
        start0=str2datetime(start)
        end=str2datetime(end)
        start1=datetime.datetime(start0.year+n,1,1)
        end0=start1-datetime.timedelta(days=1)
        while True:
            if end0<end:
                yield start0,end0
                start0=start1
                start1 = datetime.datetime(start0.year + n, 1, 1)
                end0 = start1 - datetime.timedelta(days=1)
            else:
                yield start0, end
                break
    else:
        start0 = str2datetime(start)
        end = str2datetime(end)
        start1 = start0+ pd.DateOffset(months=n)
        start1 = datetime.datetime(start1.year, start1.month, 1)
        end0 = start1 - datetime.timedelta(days=1)
        while True:
            if end0 < end:
                yield start0, end0
                start0 = start1
                start1 = start0 + pd.DateOffset(months=n)
                start1 = datetime.datetime(start1.year, start1.month, 1)
                end0 = start1 - datetime.timedelta(days=1)
            else:
                yield start0, end
                break

if __name__=="__main__":
    iter=iter_start_end("20240102","20250531",by="month",n=1)
    for i in iter:
        print(i)
